<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.bpmBizTitle"
                    placeholder="请输入标题"
                    :max-length="255"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="closePdtBillNo">
                  <a-input placeholder="请输入单据编号" v-model="model.closePdtBillNo" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep :multi="false" v-model="model.proposer" disabled></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart v-model="model.proposerDeptId" disabled placeholder="请输入申请部门" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.proposerTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="封闭信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <a-input
                    v-if="formDisabled"
                    readOnly
                    @click.prevent="onDetail(model.projectId)"
                    v-model="model.projectName"
                    style="color: #1890FF; cursor: pointer;"
                    placeholder="请选择项目名称"></a-input>
                  <select-project-distribution-input
                    v-else
                    :disabled="formDisabled"
                    projectStatus="2"
                    :proDisabled="true"
                    :isContractManager="true"
                    :isProductionClose="true"
                    v-model="model.projectId"
                    placeholder="请选择项目名称"
                    @input="onChangeProjectName"></select-project-distribution-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectNo">
                  <a-input disabled v-model="model.projectNo" :max-length="36" placeholder="请输入项目编号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamName">
                  <select-team-input
                    disabled
                    v-model="model.teamName"
                    :tdlx="1"/>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="业务名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectTaskId">
                  <SelectTaskFileInput
                    :disabled="formDisabled"
                    v-model="model.projectTaskId"
                    :allowClear="false"
                    :projectId="model.projectId"
                    :isShowCategoryName="true"
                    :isProjectTaskId="true"
                    @input="taskChangeBackHandle" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="任务编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input v-model="model.billNo" :max-length="36" placeholder="请输入任务编号" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="实施部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="executeDepart">
                  <j-select-depart v-model="model.executeDepart" placeholder="请选择实施部门" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeam">
                  <select-team-input
                    v-model="model.productTeam"
                    :tdlx="1"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectLeading">
                  <select-user-by-dep
                    v-model="model.projectLeading"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="封闭开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="closeStartDate">
                  <a-date-picker
                    :disabled="formDisabled"
                    placeholder="请选择任职封闭开始时间"
                    valueFormat="YYYY-MM-DD"
                    @change="handleChange"
                    v-model="model.closeStartDate"
                    style="width: 100%" />
                  <!-- <j-date :disabled="formDisabled" placeholder="请选择封闭开始时间" v-model="model.closeStartDate" style="width: 100%" /> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="封闭结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="closeEndDate">
                  <a-date-picker
                    :disabled="formDisabled"
                    :disabled-date="disabledDate"
                    :default-picker-value="this.model.closeStartDate"
                    placeholder="请选择封闭结束时间"
                    valueFormat="YYYY-MM-DD"
                    v-model="model.closeEndDate"
                    style="width: 100%" />
                  <!-- <j-date :disabled="formDisabled" placeholder="请选择封闭结束时间" v-model="model.closeEndDate" style="width: 100%" /> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="封闭人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="closeUserNames">
                  <select-user-by-dep :multi="true" v-model="model.closeUserNames" :disabled="formDisabled"></select-user-by-dep>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="申请原因" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="closeApplyReason">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.closeApplyReason" rows="4" placeholder="请输入申请原因"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="预期成果" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="expectResult">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.expectResult" rows="4" placeholder="请输入预期成果"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>

            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachmentFile">
                  <j-upload :disabled="formDisabled" v-model="model.attachmentFile" ></j-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </j-form-container>

    <a-row type="flex" justify="center">
      <a-col :span="24">
        <!-- 流程历史跟踪 -->
        <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData"></common-flow-list>
      </a-col>
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton ? '10px' : '0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <!-- 项目详情开始 -->
    <erp-project-report-modal ref="projectModalForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->
    <ErpProductionCloseFormPrint v-if="formBpm" id="printClose" class="print_style" :formData="model" :formDataHistory="formData"></ErpProductionCloseFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput' // 经营团队
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import SelectTaskFileInput from '@/views/scy/components/SelectTaskFileInput' // 业务名称
  import SelectProjectDistributionInput from '@/views/scy/components/SelectProjectDistributionInput'; //  项目名称
  import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import ErpProductionCloseFormPrint from './ErpProductionCloseFormPrint.vue';
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import Print from '@/utils/print/printarea.js';
  export default {
    name: 'ErpProductionCloseForm',
    components: {
      SelectUserByDep,
      SelectTeamInput,
      SelectCompanyInput,
      SelectCustomerInput,
      SelectProjectDistributionInput,
      SelectTaskFileInput,
      ErpProjectReportModal,
      CommonFlowList,
      ErpProductionCloseFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model: {
        },
        labelCol: {
        },
        activeKey: ['1', '2', '3'],
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          closePdtBillNo: [{ required: true, message: '请重新生成单据编号!' }],
          proposer: [{ required: true, message: '请重新生成申请人!' }],
          proposerDeptId: [{ required: true, message: '请重新生成申请部门!' }],
          proposerTime: [{ required: true, message: '请重新生成申请时间!' }],
          projectId: [{ required: true, message: '请选择项目名称!' }],
          projectTaskId: [{ required: true, message: '请选择业务名称!' }],
          closeStartDate: [{ required: true, message: '请选择封闭开始时间!' }],
          closeEndDate: [{ required: true, message: '请选择封闭结束时间!' }],
          closeApplyReason: [{ required: true, message: '请输入申请原因!' }],
          expectResult: [{ required: true, message: '请输入预期成果!' }],
          closeUserNames: [{ required: true, message: '请选择封闭人员!' }]
        },
        url: {
          add: '/api/erp/closeProdution/erpProductionClose/add',
          edit: '/api/erp/closeProdution/erpProductionClose/edit',
          queryById: '/api/erp/closeProdution/erpProductionClose/queryById',
          generatedFormNumber: '/api/erp/base/generatedFormNumber'
        }
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),
      moment,
      // 获取单据编号
    generatedFormNumber() {
      getAction(this.url.generatedFormNumber, { prefix: 'FBSC', subSystemCode: '05' }).then(res => {
        if (res.success) {
          this.$set(this.model, 'closePdtBillNo', res.result)
        }
      })
    },
    handleChange(value) {
      if (value) {
        if (this.model.closeEndDate) {
          if (moment(this.model.closeEndDate).diff(moment(this.model.closeStartDate), 'days') < 0) {
            this.model.closeEndDate = this.model.closeStartDate
          }
        }
      } else {
        this.model.closeEndDate = ''
      }
    },
    disabledDate(current) {
      return current < moment(this.model.closeStartDate).subtract('day')
    },
    async onChangeProjectName (item) {
      var event = await item.choseObj[0]
      if (event) {
        this.$set(this.model, 'projectName', event.projectName) // 项目名称
        this.$set(this.model, 'projectNo', event.finalNo) // 项目编号
        this.$set(this.model, 'teamName', event.oldTeamId ? event.oldTeamId : event.teamName) // 经营团队
      } else {
        this.$set(this.model, 'projectNo', '') // 项目编号
        this.$set(this.model, 'projectName', '') // 项目名称
        this.$set(this.model, 'teamName', '') // 经营团队
      }
      this.$set(this.model, 'projectTaskId', '')
      this.$set(this.model, 'billNo', '')
      this.$set(this.model, 'executeDepart', '')
      this.$set(this.model, 'productTeam', '')
      this.$set(this.model, 'projectLeading', '')
      this.$set(this.model, 'categoryCode', '')
      this.$set(this.model, 'categoryName', '')
    },

    // 业务名称选择回调
    taskChangeBackHandle(item) {
      let task = item.choseObj[0];
      if (task) {
        // 带出任务编号
        this.$set(this.model, 'billNo', task.billNo)

        // 带出实施部门
        this.$set(this.model, 'executeDepart', task.executeDepart)

        // 带出生产团队
        this.$set(this.model, 'productTeam', task.productTeam)

        // 带出项目负责人
        this.$set(this.model, 'projectLeading', task.projectLeading)

        // 带出业务编码
        this.$set(this.model, 'categoryCode', task.categoryCode)

        // 带出业务名称
        this.$set(this.model, 'categoryName', task.categoryName)
      }
    },
      add () {
        this.$set(this.modelDefault, 'proposerTime', moment().format('YYYY-MM-DD HH:mm:ss')) // 申请人
        this.$set(this.modelDefault, 'proposer', this.userInfo().empId) // 申请人
        this.$set(this.modelDefault, 'proposerDeptId', this.userInfo().deptId) // 申请人
        this.edit(this.modelDefault);
        this.generatedFormNumber()
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },

      onDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryProjectById, { id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectModalForm.getDetail(model);
              that.$refs.projectModalForm.title = '项目一览表';
            }
          })
        })
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint() {
        let print = new Print({
          el: '#printClose',
          popTitle: '封闭生产申请单详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
